package c2.group.business.teampvp.sub;

import c2.group.business.base.GroupSubModule;
import c2.group.business.teampvp.TeamPvpInvite;
import c2.group.business.teampvp.TeamPvpModule;
import cate.common.util.GameResult;
import org.springframework.data.annotation.Transient;

import java.util.*;

public class TeamPvpInviteModule extends GroupSubModule<TeamPvpModule> {
    @Transient
    private Map<String, TeamPvpInvite> invitedMap;
    private final Object inviteLock = new Object();

    @Override
    public void initDependent() {
        this.invitedMap = useDb().teamPvp.getInvites();
    }

    public void seasonReset() {
        synchronized (inviteLock) {
            invitedMap.clear();
        }
    }

    public GameResult<Void> addInvites(String invitedUid, String leaderUid) {
        GameResult<Void> r = new GameResult<>();
        synchronized (inviteLock) {
            TeamPvpInvite invite = invitedMap.computeIfAbsent(invitedUid, e -> new TeamPvpInvite(invitedUid));
            if (invite.contains(leaderUid)) {
                return r.fail("您已经邀请过该玩家了");
            }
            if (invite.size() >= 20) {
                return r.fail("该玩家邀请列表已满");
            }
            invite.addInviter(leaderUid);
        }
        return r.success("邀请成功");
    }

    public void answerInvite(String inviteUid, String leaderUid) {
        synchronized (inviteLock) {
            TeamPvpInvite invite = invitedMap.get(inviteUid);
            if (invite != null) {
                invite.remove(leaderUid);
            }
        }
    }

    public boolean hasInvited(String leaderUid, String invitedUid) {
        synchronized (inviteLock) {
            return invitedMap.containsKey(invitedUid) && invitedMap.get(invitedUid).contains(leaderUid);
        }
    }

    public List<String> getInviteApplys(String inviteUid) {
        synchronized (inviteLock) {
            TeamPvpInvite invite = invitedMap.get(inviteUid);
            return invite == null ? Collections.emptyList() : invite.invites;
        }
    }

    @Override
    public void onShutdown() {
        useDb().teamPvp.saveInvites(invitedMap.values());
    }
}
